package com.qs.main.ui;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.MainThread;
import android.view.View;
import android.widget.FrameLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.luck.picture.lib.tools.ToastManage;
import com.qs.base.base.BaseMyActivity;
import com.qs.base.global.SPKeyGlobal;
import com.qs.base.router.RouterActivityPath;
import com.qs.base.utils.BaseTimeUtils;
import com.qs.main.BR;
import com.qs.main.R;
import com.qs.main.databinding.MainStartupPageActivityBinding;

import java.util.Date;

import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * 启动页
 *
 * @Author ltzz
 * @Date 2019/8/28
 */
public class StartupPageActivity extends BaseMyActivity<MainStartupPageActivityBinding, StartupPageViewModel> {

    private TTAdNative mTTAdNative;
    private FrameLayout mSplashContainer ;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.main_startup_page_activity;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected boolean statusBarDarkFont() {
        return false;
    }

    @Override
    protected View titleLayout() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSplashContainer = findViewById(R.id.mSplashContainer);
        //step2:创建TTAdNative对象
        mTTAdNative = TTAdManagerHolder.get().createAdNative(this);

        //测试数据
//        SPUtils.getInstance().put(SPKeyGlobal.USER_ID, "");
//        SPUtils.getInstance().put(SPKeyGlobal.LAST_DATE, -1l);
//        SPUtils.getInstance().put(SPKeyGlobal.USER_DATE, "");

        //初始化数据
        String userid = SPUtils.getInstance().getString(SPKeyGlobal.USER_ID);
        if (!StringUtils.isTrimEmpty(userid)) {
            //用户已登录
            //获取会员信息
            viewModel.getVIPInfo(userid);
        } else
            viewModel.setData(false);


        if(DataHelper.getStringSF(this ,"wzfy_dialog") == null){
            DialogHomeUtils.showLoading(this, new DialogHomeUtils.OnClick() {
                @Override
                public void goIntent() {
                    DialogHomeUtils.stopLoading();
                    DataHelper.setStringSF(StartupPageActivity.this ,"wzfy_dialog","1");
                    loadSplashAd();
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            goToMainActivity();
//                        }
//                    },2000);
                }
            });
        }else{
            loadSplashAd();
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    goToMainActivity();
//                }
//            },2000);
        }

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(2000);
//                    handler.sendMessage(new Message());
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }


    /**
     * 加载开屏广告
     */
    private void loadSplashAd() {
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = null;
        adSlot = new AdSlot.Builder()
                .setCodeId("887294382")
                .setSupportDeepLink(true)
                .setImageAcceptedSize(1080, 1920)
                .build();

        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            @Override
            @MainThread
            public void onError(int code, String message) {
//                Log.d(TAG, String.valueOf(message));
//                showToast(message);
                goToMainActivity();
            }

            @Override
            @MainThread
            public void onTimeout() {
                ToastManage.s(StartupPageActivity.this ,"开屏广告加载超时");
                goToMainActivity();
            }

            @Override
            @MainThread
            public void onSplashAdLoad(TTSplashAd ad) {
//                Log.d(TAG, "开屏广告请求成功");
                if (ad == null) {
                    return;
                }
                //获取SplashView
                View view = ad.getSplashView();
                if (view != null && mSplashContainer != null && !StartupPageActivity.this.isFinishing()) {
                    mSplashContainer.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                    mSplashContainer.addView(view);
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                    //ad.setNotAllowSdkCountdown();
                }else {
                    goToMainActivity();
                }

                //设置SplashView的交互监听器
                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {
                        ToastManage.s(StartupPageActivity.this ,"开屏广告点击");
                    }

                    @Override
                    public void onAdShow(View view, int type) {
//                        ToastUtil.makeText(StartPageActivity.this ,"开屏广告展示");
                    }

                    @Override
                    public void onAdSkip() {
//                        Log.d(TAG, "onAdSkip");
//                        showToast("开屏广告跳过");
                        goToMainActivity();

                    }

                    @Override
                    public void onAdTimeOver() {
//                        Log.d(TAG, "onAdTimeOver");
//                        showToast("开屏广告倒计时结束");
                        goToMainActivity();
                    }
                });
                if(ad.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
                    ad.setDownloadListener(new TTAppDownloadListener() {
                        boolean hasShow = false;

                        @Override
                        public void onIdle() {

                        }

                        @Override
                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                            if (!hasShow) {
                                ToastManage.s(StartupPageActivity.this ,"下载中...");
                                hasShow = true;
                            }
                        }

                        @Override
                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                            ToastManage.s(StartupPageActivity.this ,"下载暂停...");

                        }

                        @Override
                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                            ToastManage.s(StartupPageActivity.this ,"下载失败...");

                        }

                        @Override
                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onInstalled(String fileName, String appName) {

                        }
                    });
                }
            }
        }, 3000);

    }

    private void goToMainActivity(){
        ARouter.getInstance().build(RouterActivityPath.Home.HOME_MAIN).navigation();
        finish();
    }

}
